#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include "led.h"
static const char * led_path[LED_MAX_NUM] = {RLED_DEV_PATH,GLED_DEV_PATH,BLED_DEV_PATH};
static struct led_info  led_control;  //全局控制变量

int get_led_lightness(unsigned char number) {
    if(number > led_control.led_open_num) {
        printf("led num error\r\n");
        return -1;
    }
    lseek(led_control.led_fd[number],0,SEEK_SET); // 重新移动到开头
    char led_brightness[4]; // 最大3位数字 + null terminator
    ssize_t read_bytes = read(led_control.led_fd[number], led_brightness, sizeof(led_brightness));
    if(read_bytes > 0) {
        led_brightness[read_bytes] = '\0'; // 手动添加字符串终止符
        return atoi(led_brightness); // 将字符串转换为整数
    } else {
        perror("read error");
        return -1; // 错误
    }
}

int write_led_lightness(unsigned char number, unsigned char brightness) {
    if(number > led_control.led_open_num) {
        printf("led num error\r\n");
        return -1;
    }
    char str[4]; // 3 digits + null terminator
    snprintf(str, sizeof(str), "%d", brightness); // 将亮度值转换为ASCII字符串
    ssize_t written = write(led_control.led_fd[number], str, strlen(str));
    if(written == strlen(str)) {
        printf("写入LED:%d成功\r\n",number);
        return 0; // 成功
    } else {
        perror("write error");
        return -1; // 错误
    }
}
int led_init()
{

    for(int i = 0; i < LED_MAX_NUM; i++)
    {
        led_control.led_fd[i] = open(led_path[i],O_RDWR);
        if (led_control.led_fd[i] == -1) {
            printf("open led %d error\r\n",i);
            led_control.led_open_num = 0;
            return -1;
        }
        led_control.led_open_num++;
    }
    return 0;

}

void led_exit()
{
    for(; led_control.led_open_num > 0; led_control.led_open_num--) {
        close(led_control.led_fd[led_control.led_open_num - 1]);
    }
    led_control.led_open_num = 0;
}